<?php
namespace app\api\controller\v1;

use x\my\pay\Alipay;
class Order extends Base{

    public function __construct() {
        parent::__construct();
        $this->checkLogin();
    }

    //添加订单
    function add(){
        $d = $this->post();
        $pay_money = $d["payPrice"];
        $rule = [
            'goods_ids' => 'require',
            'address_id' => 'require',
            'payPrice' => 'require',
        ];
        $msg = [
            'goods_ids.require' => '未选中商品',
            'address_id.require' => '未选择收货地址',
            'payPrice.require' => '参数错误',
        ];
        check($rule, $msg, $d);
        $goods_ids = $d['goods_ids'];
        $temp = explode(',',$goods_ids);
        $temp1 = [];
        $temp2 = [];
        foreach ($temp as $k => $v) {
            $temp1 = explode('|',$v);
            $temp2[$temp1[0]] = $temp1[1];
        }
        //创建订单编号
        $order_goods_no = com_order_no();
        $model = m("orderGoods", "c");
        $rs = $model->createOrder($this->userinfo['id'], $temp2, $order_goods_no, $d["address_id"]);
        if ($rs) {
            //删除购物车商品
            foreach ($temp2 as $k => $v) {
                $this->db->query('delete from order_cart where user_id = ? and goods_price_id = ?',[$this->userinfo['id'],$k]);
            }
            //如果用户余额大于订单总价，支付成功
            if ($rs['total_money'] <= $this->userinfo['money']) {
                $this->payOk($order_goods_no);
            }
            //充值余额
            $order_no = m('recharge', 'c')->rechargeMoney($this->userinfo['id'], $pay_money, 1);
            if ($order_no) {
                $pay = new Alipay();
                $formhtml = $pay->buildRequestForm($order_no, $pay_money, '消费充值');
                suc(['formhtml' => $formhtml, 'order_no' => $order_no, "order_goods_no" => $order_goods_no]);
            }

        }
        err("订单创建失败");
    }

    /**
     * [payOk 订单支付成功]
     * @param  string $order_no [订单编号]
     * @return [type]           [json]
     */
    private function payOk($order_no = '') {
        if (!$order_no) {
            err("参数错误!");
        }
        //查询商品订单
        $map = [];
        $map[] = ["and", "order_no", "=", $order_no];
        $w = where($map);
        $order_goods_list = $this->db->query("select * from order_goods $w[0]", $w[1]);
        if (empty($order_goods_list)) {
            err("订单不存在!");
        }
        $order_total_price = $order_goods_list[0]['order_total_money'];
        if ($this->userinfo["money"] < $order_total_price) {
            err("用户余额不足!");
        }
        $this->db->begin();
        $mysql = [];
        //修改订单支付状态
        $d = ["pay_status" => 1];
        $map = ['order_no=?', [$order_no]];
        $mysql[] = $this->db->update("order_goods", $d, $map);
        #插入账单
        $mysql[] = m('Userbill', 'xcom')->doit($order_no, $this->userinfo['id'], 200, 'order_goods', $order_goods_list[0]['id'], $order_total_price,'money','消费', 0);
        $rs = $this->db->end($mysql);
        if (!$rs) {
            log_test('wxpay_result_db', $mysql);
            err('支付账单失败');
        }
        suc('支付成功');
    }

    //订单列表
    public function lists(){
        $page = $this->post('page',1);
        $goodsname = $this->get('goodsname');
        $fahuostatus = $this->get('fahuostatus');
        $limit = $this->post('limit',11);
        $d = $this->post();
        $order = 0;
        $map = [];
        if($fahuostatus || $fahuostatus!==''){
            $map[] = ["and","fahuo_status","=",$fahuostatus];
        }
        $map[] = ["and","user_id","=",$this->userinfo["id"]];
        if($goodsname)$map[] = ['and',"(order_no like ? or title like ?)",["%{$goodsname}%","%{$goodsname}%"]];
        $w = where($map);
        $rs = $this->db->query("select * from order_goods {$w[0]} order by id desc".limit($page,$limit),$w[1],'',true);
        if($rs){
          $rule = [
              'create_time' => 'com_time_format',
          ];
          $data = com_format($rs[0],$rule);
        }
        $list = [
            "goodslist"=>$data,
            "page_count"=>$rs[1],
            "max_page"=>ceil($rs[1]/10),
            "page" => $page,
        ];
        suc($list);
    }

    //订单商品评价
    public function evaluate(){
        $id = $this->post('id');
        $order = $this->db->find('order_goods',$id);
        $info  = $this->db->query('select * from goods_evaluate where order_goods_id = ?',[$id],1);
        suc(['info'=>$info,'order'=>$order]);
    }

    //保存订单商品评价
    public function saveEvaluate(){
        $d = $this->post();
        $rule = [
            'checked'=>'require',
            'order_goods_id'=>'require',
            'goods_id'=>'require',
            'goods_price_id'=>'require',
            'content'=>'require',
        ];
        $msg = [
            'checked.require' => '请确认收货后,才能评价',
            'order_goods_id.require' => '订单ID不能为空',
            'goods_id.require' => '商品ID不能为空',
            'goods_price_id.require' => '规格ID不能为空',
            'content.require' => '请输入您的评价',
        ];
        check($rule,$msg,$d);
        $d['user_id'] = $this->userinfo["id"];
        $d['create_time'] = time();
        $d['update_time'] = time();
        unset($d['checked']);
        unset($d['url']);
        unset($d['token']);
        unset($d['app_key']);
        unset($d['sign']);
        $this->db->insert('goods_evaluate',$d);
        $data = [
            'id' => $d['order_goods_id'],
            'sh_status' => 1,
        ];
        $this->db->update('order_goods',$data);

        suc('评价成功!');
    }

    //申请退款
    public function applyRefund(){
        $d = $this->post();
        $rule = [
            'order_id'=>'require',
        ];
        $msg = [
            'order_id.require' => '订单ID不能为空',
        ];
        check($rule,$msg,$d);
        if(!isset($d['order_id'])){
            err("参数错误!");
        }
        $info = $this->db->query('select * from order_goods where id=? and user_id=?',[$d['order_id'],$this->userinfo['id']],1);
        if(!$info){
            err("订单不存在!");
        }
        $m = m('orderGoods','c');
        $rs = $m->apply_refund($d['order_id']);
        if($rs){
            suc('申请成功!');
        }else{
            err($m->getError());
        }

    }

}
?>
